<?php
namespace app\admin\controller;

use think\Controller;
use think\Request;
use think\Db;
use think\Session;
use app\admin\model\LogStaffLogins;

class Login extends Controller
{
   public function login(){
       return view();
   }

   public function checkLogin(){
       if(Request::instance()->isAjax()){
            $post = Request::instance()->post();
            $post = $post['data'];
            //检查验证码

           if(captcha_check($post['captcha'])){
               //检查账号密码
               //加密方式
               $hasher = new \PasswordHash(8, false);
               $check = Db::name('admin')->where("admin_name = '{$post['admin_name']}'")->find();
               //return $check;die;
               if($check){
                    if($check['is_use']==0){
                        return ['code'=>'账号已被禁用,请联系管理员'];
                    }
                   if ($hasher->CheckPassword($post['admin_password'], $check['admin_password'])){
                       Session::set('admin_id',$check['admin_id']);
                       Session::set('admin_relname',$check['admin_relname']);
                       //检查前台是否有手机号
//                       $phone = Db::name('user')->where('phone',$check['admin_phone'])->find();
//                       if(empty($phone)){
//                           return ['code'=>'请先去pc或客户端注册用户'];
//                       }else{
//                           Session::set('index_uid',$phone['uid']);
//                       }
                       //修改上次登录时间和ip
                       $saveData = array(
                           'lasttime'=>date('Y-m-d H:i:s'),
                           'lastip'=>Request::instance()->ip()
                       );
                       Db::name('admin')->where('admin_id',$check['admin_id'])->setField($saveData);
                       //记录登录日志
                       LogStaffLogins::create([
                           'staff_id'=>session('admin_id'),
                           'login_time'=> time(),
                           'login_ip'=>request()->ip()
                       ]);
                       return ['code'=>0];
                   }else{
                       return ['code'=>'密码错误'];
                   }

               }else{
                   return ['code'=>'账号不存在'];
               }
           }else{
               return ['code'=>'验证码错误'];
           };
       }
   }
}
